//
//  CommitCommentViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/30.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CommitCommentViewController.h"
#import "StarsView.h"
#import "PhotoSheetView.h"
#import "UICustomActionSheet.h"
#import "STActionSheet.h"
#import "DZNPhotoEditorViewController.h"
#import "UIImagePickerController+Edit.h"
#import "UIImageView+WebCache.h"
#import <UIImageView+RJLoader.h>
#import "CommentIndentTableViewCell.h"
#import "PhotoPopView.h"
static NSString * cellIndentifier = @"CommentIndentTableViewCell";
@interface CommitCommentViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *startsView;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;

@property(nonatomic,strong)NSMutableDictionary * photoDic;

@property(nonatomic,assign)CGFloat serviceCode;
@property(nonatomic,assign)CGFloat goodsCode;
@property(nonatomic,strong)NSString * showOrNot;
@property(nonatomic,strong)NSIndexPath * currentIndexpath;
@end

@implementation CommitCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _showOrNot = @"1";
    _serviceCode = 10;
    _goodsCode = 10;
    _photoDic = [NSMutableDictionary dictionary];
    [self initViewLayout];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout: self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.startsView];
    NSArray * array = _goodsInfoDic[@"goodsList"];
    _tableView.frame = flexibleFrame(CGRectMake(0, 0, 320, array.count*310), YES);
    _startsView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_tableView.frame), 320, _startsView.frame.size.height), YES);
    _scroView.contentSize = flexibleSize(CGSizeMake(0, CGRectGetHeight(_tableView.frame)+CGRectGetHeight(_startsView.frame)), NO);
  
    
    StarsView * serviceStars = [[StarsView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 40, 305, 45), NO) Title:@"服务评分" numberOfStars:5 complect:^(CGFloat index) {
        _serviceCode = index;
    }];
    [_startsView addSubview:serviceStars];
    
    StarsView * goodsStars = [[StarsView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 75, 305, 45), NO) Title:@"商品评分" numberOfStars:5 complect:^(CGFloat index) {
        _goodsCode = index;
    }];
    [_startsView addSubview:goodsStars];
    
     [self.tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;

    
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

- (IBAction)goHome:(id)sender {
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
    [self.navigationController  popViewControllerAnimated:YES];
}
- (void)addPhoto{
    
    NSArray * Array = _photoDic[_currentIndexpath];
    if (Array.count>=3) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片不能超过三张" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        return;
    }
    
    
    PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    NSMutableArray * array = _photoDic[_currentIndexpath];
                    imageButton.frame = flexibleFrame(CGRectMake(12+66*array.count, 100, 65, 65), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    CommentIndentTableViewCell * cell = [_tableView cellForRowAtIndexPath:_currentIndexpath];
                    [cell addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    NSMutableArray * array = _photoDic[_currentIndexpath];
                    imageButton.frame = flexibleFrame(CGRectMake(12+66*array.count, 100, 65, 65), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    CommentIndentTableViewCell * cell = [_tableView cellForRowAtIndexPath:_currentIndexpath];
                    [cell addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    NSMutableArray * array = _photoDic[_currentIndexpath];
                    imageButton.frame = flexibleFrame(CGRectMake(12+66*array.count, 100, 65, 65), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    CommentIndentTableViewCell * cell = [_tableView cellForRowAtIndexPath:_currentIndexpath];
                    [cell addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    NSMutableArray * array = _photoDic[_currentIndexpath];
                    imageButton.frame = flexibleFrame(CGRectMake(12+66*array.count, 100, 65, 65), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    CommentIndentTableViewCell * cell = [_tableView cellForRowAtIndexPath:_currentIndexpath];
                    [cell addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
        }
        
    }];
    [photoPopView show];

    
}

#pragma mark == 提交评论
- (IBAction)commitComment:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSArray *goodsList =    _goodsInfoDic[@"goodsList"];
    NSString *mgcoContent = @"";
    NSString *mgcoOrderDetailId = @"";
    NSString *mgcoCommentLevel = @"";
    NSString *mgcoGoodsupSpecity = @"";
    NSString * mgcImageId = @"";
    for (int i=0; i<goodsList.count; i++) {
        if(i==0){
            mgcoContent = _goodsInfoDic[@"goodsList"][i][@"mstoAddress"];
            mgcoContent=[mgcoContent stringByReplacingOccurrencesOfString:@","withString:@"，"];
            mgcoOrderDetailId = _goodsInfoDic[@"goodsList"][i][@"maorDetailId"];
            mgcoCommentLevel = _goodsInfoDic[@"goodsList"][i][@"mstoPhone"];
            mgcoGoodsupSpecity = _goodsInfoDic[@"goodsList"][i][@"mgspId"];
            NSMutableArray * array = _photoDic[[NSIndexPath indexPathForRow:i inSection:0]];
            NSString * imageId;
            for (int j = 0; j<array.count; j++) {
                if (j==0) {
                    imageId = [NSString stringWithFormat:@"%@",array[j]];
                }else{
                    imageId = [NSString stringWithFormat:@"%@,%@",imageId,array[j]];
                }
            }
            mgcImageId = [NSString stringWithFormat:@"%@",imageId];
        }else{
            mgcoContent = [NSString stringWithFormat:@"%@,%@",mgcoContent,_goodsInfoDic[@"goodsList"][i][@"mstoAddress"]];
            mgcoContent=[mgcoContent stringByReplacingOccurrencesOfString:@","withString:@"，"];
            mgcoOrderDetailId = [NSString stringWithFormat:@"%@,%@",mgcoOrderDetailId,_goodsInfoDic[@"goodsList"][i][@"maorDetailId"]];
            mgcoCommentLevel = [NSString stringWithFormat:@"%@,%@",mgcoCommentLevel,_goodsInfoDic[@"goodsList"][i][@"mstoPhone"]];
            mgcoGoodsupSpecity = [NSString stringWithFormat:@"%@,%@",mgcoGoodsupSpecity,_goodsInfoDic[@"goodsList"][i][@"mgspId"]];
            NSMutableArray * array = _photoDic[[NSIndexPath indexPathForRow:i inSection:0]];
            NSString * imageId;
            for (int j = 0; j<array.count; j++) {
                if (j==0) {
                    imageId = [NSString stringWithFormat:@"%@",array[j]];
                }else{
                    imageId = [NSString stringWithFormat:@"%@,%@",imageId,array[j]];
                }
            }
            mgcImageId = [NSString stringWithFormat:@"%@;%@",mgcImageId,imageId];
        }
        
        
    }
    //用地址字段存放评价内容
    [dic setObject:mgcoContent forKey:@"mgcoContent"];
    [dic setObject:mgcoOrderDetailId forKey:@"orderDetailIds"];
    [dic setObject:mgcoCommentLevel forKey:@"commentLevels"];
    [dic setObject:mgcoGoodsupSpecity forKey:@"goodsupSpecitys"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"mgcoMemberId"];
    [dic setObject:[Common getLoginInfo][@"nickname"] forKey:@"mgcoAuthor"];
    
    [dic setObject:[NSString stringWithFormat:@"%ld",(NSInteger)_goodsCode*2] forKey:@"mgcoCommentStars"];
    [dic setObject:[NSString stringWithFormat:@"%ld",(NSInteger)_serviceCode*2] forKey:@"mgcoServiceStars"];
    [dic setObject:_showOrNot forKey:@"mgcoIsAnonymous"];
    [dic setObject:mgcImageId forKey:@"strTime"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_saveGoodsOrderComment withHttpType:@"POST" withTag:SX_SX_saveGoodsOrderComment];
    
}
- (IBAction)showNameOrNot:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _showOrNot = @"1";
    }else{
    _showOrNot = @"0";
    }
}

#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = SX_uploadCommentImg;
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.5);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [Common shaEncrypt:[[Common getLoginInfo] objectForKey:Key_User_password]];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    NSMutableArray * array = _photoDic[_currentIndexpath];
    [array addObject:image];
    [_photoDic setObject:array forKey:_currentIndexpath];
    CommentIndentTableViewCell * cell = [_tableView cellForRowAtIndexPath:_currentIndexpath];
    cell.addPhotoButton.frame = flexibleFrame(CGRectMake(12+66*array.count, 100, 65, 65), YES);


    
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 225*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * array = _goodsInfoDic[@"goodsList"];
    return array.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentIndentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (cell == nil) {
        cell= [[CommentIndentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    
        NSDictionary * dic = _goodsInfoDic[@"goodsList"][indexPath.row];
        NSString * image = dic[@"appAdertImagUriName"];
        if (image.length>0) {
            [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            cell.goodsImage.image =[UIImage imageNamed:@"cloth1"];
        }
    //地址字段存放评论内容
    cell.addCommentBlock = ^(NSString * str){
        _goodsInfoDic[@"goodsList"][indexPath.row][@"mstoAddress"] = str;
    };
    //地址电话存放评论等级
    cell.commentLevelBlock = ^(NSString * str){
        _goodsInfoDic[@"goodsList"][indexPath.row][@"mstoPhone"] = str;
    };
    
    cell.addPhotoBlock = ^(NSString * str){
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        NSMutableArray * array = _photoDic[indexPath];
        if (!array) {
            _currentIndexpath = indexPath;
            NSMutableArray * array = [NSMutableArray array];
            [_photoDic setObject:array forKey:indexPath];
        }
        [self addPhoto];
    };
    
    
    return cell;
}




#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    
    if (tag==SX_SX_saveGoodsOrderComment) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            [self.navigationController  popViewControllerAnimated:YES];
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  ];
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
